package com.cxyzy.clipboardmonitor

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.ClipDescription
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import org.greenrobot.eventbus.EventBus


/**
 * 监控剪贴板
 * 安卓Q开始，不能再监控剪贴板了。
 */
class ClipBoardMonitorService : Service(), ClipboardManager.OnPrimaryClipChangedListener {

    companion object {
        const val ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE"

        const val ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE"
    }

    private lateinit var clipboardManager: ClipboardManager


    private val iBinder: IBinder = LocalBinder()


    class LocalBinder : Binder() {

        fun getService(): ClipBoardMonitorService {
            return getService()
        }
    }

    /** method for clients  */
    val currentStrInClipBrd: String
        get() = clipboardManager.primaryClip!!.getItemAt(0).toString()


    override fun onCreate() {
        super.onCreate()
        clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        clipboardManager.addPrimaryClipChangedListener(this)
    }

    override fun onPrimaryClipChanged() {
        val clipData = clipboardManager.primaryClip
        if (clipData != null && clipData.itemCount > 0) {
            val item = clipData.getItemAt(0)
            val clipDescription = clipData.description
            var newStr = ""
            if (clipData.itemCount > 0 && clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                if (item.text != null) {
                    newStr = item.text.toString()
                }
            } else if (clipData.itemCount > 0 && clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML)) {
                newStr = item.text.toString()
            }
            EventBus.getDefault().post(newStr)
        }
    }


    override fun onBind(intent: Intent?): IBinder? {

        return iBinder
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent != null) {
            val action = intent.action

            if (action != null) {
                when (action) {
                    ACTION_START_FOREGROUND_SERVICE -> {
                        startForegroundService()
                    }
                    ACTION_STOP_FOREGROUND_SERVICE -> {
                        stopForegroundService()
                    }
                }
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    private fun startForegroundService() {
        if (Build.VERSION.SDK_INT >= 26) {
            val CHANNEL_ID = "my_channel_01"
            val channel = NotificationChannel(
                CHANNEL_ID,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
                channel
            )
            val activityIntent = Intent(this, MainActivity::class.java)
            val pendingActivityIntent = PendingIntent.getActivity(this, 0, activityIntent, 0)
            val serviceIntent = Intent(this, ClipBoardMonitorService::class.java)
            serviceIntent.action = ACTION_STOP_FOREGROUND_SERVICE

            val pStopSelf =
                PendingIntent.getService(this, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT)
            val action = NotificationCompat.Action.Builder(0, "STOP", pStopSelf).build()
            val notification = NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Clipboard Monitoring..")
                //.setContentText("Click on stop to monitor")
                .setSmallIcon(R.drawable.ic_logo)
                .addAction(action)
                .setContentIntent(pendingActivityIntent).build()
            startForeground(1, notification)
        }
    }

    private fun stopForegroundService() {
        stopForeground(true)
        stopSelf()
    }
}